package com.runa.protocol.analysis;

import com.runa.protocol.enums.ByteOrder;
import com.runa.protocol.enums.ModbusFunctionCode;
import com.runa.protocol.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhuj
 */
public class ModbusBufferTCPAnalysis extends MetaBufferAnalysis<byte[]> {

    private static final Logger logger = LoggerFactory.getLogger(ModbusBufferTCPAnalysis.class);

    @Override
    public int fill(byte[] data, int size,String netEquNo) {
        responseData = null;
        if (size < 6) {
            return -1;
        }
        int len = ((data[4] & 0xff) << 8) + (data[5] & 0xff) + 6;
        if (size < len) {
            return -1;
        }
        short transSign = ByteUtil.byteToShort(data, 0, ByteOrder.AB);
        int slave = data[6] & 0xff;
        ModbusFunctionCode funCode = ModbusFunctionCode.getByCode(data[7] & 0xff);
        int cap;
        if (funCode.isReadOrWrite()) {
            cap = len - 9;
            System.arraycopy(data, 9, data, 0, cap);
        } else {
            cap = 4;
            System.arraycopy(data, 8, data, 0, cap);
        }
        buffer = data;
        createModbusResponse(slave, transSign, funCode, cap);
        return size - len;
    }

}
